package com.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.entity.Address;
import com.bookstore.mapper.AddressMapper;
import com.bookstore.service.AddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    private static final int MAX_ADDRESS_COUNT = 20;

    @Override
    @Transactional
    public boolean addAddress(Address address) {
        // 检查用户地址数量
        long count = count(new LambdaQueryWrapper<Address>()
                .eq(Address::getUserId, address.getUserId()));
        if (count >= MAX_ADDRESS_COUNT) {
            throw new IllegalArgumentException("收货地址数量已达上限");
        }

        // 如果是默认地址，需要将其他地址设置为非默认
        if (Boolean.TRUE.equals(address.getIsDefault())) {
            resetDefaultAddress(address.getUserId());
        }
        // 如果是用户的第一个地址，自动设置为默认地址
        else if (count == 0) {
            address.setIsDefault(true);
        }

        return save(address);
    }

    @Override
    @Transactional
    public boolean updateAddress(Address address) {
        Address existingAddress = getById(address.getAddressId());
        if (existingAddress == null) {
            throw new IllegalArgumentException("地址不存在");
        }

        // 如果设置为默认地址，需要将其他地址设置为非默认
        if (Boolean.TRUE.equals(address.getIsDefault())) {
            resetDefaultAddress(address.getUserId());
        }

        return updateById(address);
    }

    @Override
    public boolean deleteAddress(Integer addressId) {
        Address address = getById(addressId);
        if (address == null) {
            throw new IllegalArgumentException("地址不存在");
        }

        // 如果删除的是默认地址，需要重新设置一个默认地址
        if (Boolean.TRUE.equals(address.getIsDefault())) {
            Address newDefault = getOne(new LambdaQueryWrapper<Address>()
                    .eq(Address::getUserId, address.getUserId())
                    .ne(Address::getAddressId, addressId)
                    .last("LIMIT 1"));
            if (newDefault != null) {
                newDefault.setIsDefault(true);
                updateById(newDefault);
            }
        }

        return removeById(addressId);
    }

    @Override
    public List<Address> getUserAddresses(Integer userId) {
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId, userId)
                .orderByDesc(Address::getIsDefault)
                .orderByDesc(Address::getCreatedAt);
        return list(queryWrapper);
    }

    @Override
    public Address getDefaultAddress(Integer userId) {
        return getOne(new LambdaQueryWrapper<Address>()
                .eq(Address::getUserId, userId)
                .eq(Address::getIsDefault, true));
    }

    @Override
    @Transactional
    public boolean setDefaultAddress(Integer addressId) {
        Address address = getById(addressId);
        if (address == null) {
            throw new IllegalArgumentException("地址不存在");
        }

        // 将其他地址设置为非默认
        resetDefaultAddress(address.getUserId());

        // 设置新的默认地址
        address.setIsDefault(true);
        return updateById(address);
    }

    private void resetDefaultAddress(Integer userId) {
        update(new LambdaUpdateWrapper<Address>()
                .eq(Address::getUserId, userId)
                .eq(Address::getIsDefault, true)
                .set(Address::getIsDefault, false));
    }
} 